<template>
  <div class="px-4">
    <collapse-transition title="数据结构">
      <div class="flex">
        <div class="w-2/5 relative border-r">
          <pre class="w-full">{{ data }}</pre>
          <div
            class="absolute right-5 top-5 w-6 h-6 flex justify-center items-center"
            hover="drop-shadow-md drop-shadow-100/50 opacity-90"
            @click="copy(JSON.stringify(data))"
          >
            <i class="iconfont icon-copy text-2xl text-light-50"></i>
          </div>
        </div>
        <div class="handler-wrapper w-3/5 h-full l-3 bg-dark-50 relative">
          <pre>{{ listToTree(deepCopy(data)) }}</pre>
          <div
            class="absolute right-5 top-5 w-6 h-6 flex justify-center items-center"
            hover="drop-shadow-md drop-shadow-100/50 opacity-90"
            @click="copy(JSON.stringify(listToTree(deepCopy(data))))"
          >
            <i class="iconfont icon-copy text-2xl text-light-50"></i>
          </div>
        </div>
      </div>
    </collapse-transition>
  </div>
</template>

<script lang="ts">
export default {
  name: 'DataTree',
};
</script>

<script setup lang="ts">
import { copy } from '@/utils/web';
import { deepCopy } from '@/utils/index';
import CollapseTransition from '@/components/CollapseTransition/index.vue';

interface DataModel {
  id: number;
  name: string;
  parentId: number;
  children?: DataModel[];
}

const data = [
  { id: 1, name: '中国', parentId: 0 },
  { id: 2, name: '河南省', parentId: 1 },
  { id: 3, name: '广东省', parentId: 1 },
  { id: 4, name: '浙江省', parentId: 1 },
  { id: 5, name: '杭州市', parentId: 4 },
  { id: 6, name: '宁波市', parentId: 4 },
  { id: 7, name: '温州市', parentId: 4 },
  { id: 8, name: '许昌市', parentId: 2 },
  { id: 9, name: '郑州市', parentId: 2 },
  { id: 10, name: '新乡市', parentId: 2 },
  { id: 11, name: '深圳市', parentId: 3 },
  { id: 12, name: '惠州市', parentId: 3 },
  { id: 13, name: '虎门市', parentId: 3 },
] as DataModel[];

function listToTree(cityList) {
  let array: DataModel[] = [];
  cityList.forEach((item) => {
    // 遍历对象数组
    item.children = cityList.filter((info) => info.parentId === item.id); // 找到每个对象的子节点
    if (item.parentId === 0) {
      array.push(item);
    }
  });
  return array;
}

console.log('handleData(data.value) :>> ', deepCopy(data));
</script>

<style scoped>
pre {
  background-color: #252836;
  color: #fff;
  font-size: 12px;
  padding: 10px 12px;
}
</style>
